'use strict';
const Service = require('egg').Service;
const { Op } = require('sequelize');

const { failRes, successRes } = require('../extend/helper');
const { Journal } = require('../exception/Journal');

function toInt (str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sProduct extends Service {
  // pc
  // 查
  async pc_s_query (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      let ProductClassWhereMap = {};
      if (params && params.label) {
        ProductClassWhereMap = {
          id: params.label
        }
      }
      const count = await ctx.model.Product.count({
        where: {
          title: {
            [Op.like]: `%${(params?.title ?? '')}%`
          },
        },
      });
      const result = await ctx.model.Product.findAndCountAll({
        where: {
          title: {
            [Op.like]: `%${(params?.title ?? '')}%` // 使用 Op.like 实现模糊匹配
          },
        },
        include: [{
          model: ctx.model.ProductClass,
          where: ProductClassWhereMap
        }, {
          model: ctx.model.Resource,
          through: {
            attributes: {
              exclude: ['id', 'resourceId', 'productId', 'createdAt', 'updatedAt']
            }
          }
        }],
        order: [['id', 'DESC']], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      })
      await Journal(ctx, { operatorType: '商品信息 -> 查询', code: 200 });
      response = successRes({
        records: (result?.rows ?? []),
        total: (count || 0),
        pageSize,
        currentPage
      });
    } catch (error) {
      console.error(error, '<---- error - 商品信息查询');
      await Journal(ctx, { operatorType: '商品信息 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 增
  async pc_s_create (params) {
    let response = null;
    const { ctx } = this;
    let transaction;
    try {
      // 建立事务对象
      transaction = await ctx.model.transaction();
      const { label, title, details } = params;
      await ctx.model.Product.create(
        {
          title,
          details,
          pcId: label
        },
        { transaction },
        { attributes: { extends: ['id', 'title', 'details'] } } // 向数据库插入特定字段
      );
      await transaction.commit();
      await Journal(ctx, { operatorType: '商品信息 -> 新增', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 商品信息新增');
      await transaction.rollback();
      await Journal(ctx, { operatorType: '商品信息 -> 新增', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 改
  async pc_s_update (params) {
    let response = null;
    let transaction;
    const { ctx } = this;
    try {
      // 建立事务对象
      transaction = await ctx.model.transaction();
      const { id, label, title, details } = params;
      await ctx.model.Product.update(
        {
          title,
          details,
          pcId: label
        },
        {
          where: { id: params.id },
          attributes: { extends: ['id'] }
        },
        { transaction }
      );
      await transaction.commit();
      await Journal(ctx, { operatorType: '商品信息 -> 编辑', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 商品信息编辑');
      await transaction.rollback();
      await Journal(ctx, { operatorType: '商品信息 -> 编辑', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删
  async pc_s_delete (params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Product.destroy(
        {
          where: { id: params.id },
        }
      );
      await Journal(ctx, { operatorType: '商品信息 -> 删除', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 商品信息删除');
      await Journal(ctx, { operatorType: '商品信息 -> 删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 详情
  async pc_s_detail (params) {
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);

      const product = await ctx.model.Product.findByPk(params.id);
      console.log('product: ', product);
      if (!product) {
        throw (401);
      }
      const result = await ctx.model.Product.getResourcesAndCount(params.id, {
        offset: (currentPage - 1) * pageSize,
        limit: pageSize,
        where: {
          name: {
            [Op.like]: `%${(params?.name ?? '')}%` // 使用 Op.like 实现模糊匹配
          }
        }
      });
      console.log('result: ', result);
      await Journal(ctx, { operatorType: '商品信息 -> 详情', code: 200 });
      response = successRes({
        records: (result?.resources ?? []),
        total: (result?.count ?? 0),
        pageSize,
        currentPage
      });
    } catch (error) {
      console.error(error, '<---- error - 商品信息详情');
      await Journal(ctx, { operatorType: '商品信息 -> 详情', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 批量挂载文件资源
  async pc_s_batchMount (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      // 1. 查询特定的产品
      const product = await ctx.model.Product.findByPk(params?.id);
      console.log('product: ', product);

      if (!product) {
        throw (401);
      }
      // 2. 查询要添加的资源
      const resourcesToAdd = await ctx.model.Resource.findAll({
        where: {
          id: (params?.resourceIds ?? []),
        },
      });
      console.log('resourcesToAdd: ', resourcesToAdd);
      // 3. 将资源添加到产品
      const createdAt = new Date();
      const updatedAt = new Date();
      await product.addResources(
        resourcesToAdd,
        {
          through: { createdAt, updatedAt },
        });
      await Journal(ctx, { operatorType: '商品信息 -> 批量挂载资源', code: 200 });
      response = successRes(200);
    } catch (error) {
      console.error(error, '<---- error - 商品信息批量挂载资源');
      await Journal(ctx, { operatorType: '商品信息 -> 批量挂载资源', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删除商品资源
  async pc_s_deleteMountProduct (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      const product = await ctx.model.Product.findByPk(params?.id);
      if (!product) {
        throw (401);
      }
      const resourcesToAdd = await ctx.model.Resource.findAll({
        where: {
          id: (params?.resourceIds ?? []),
        },
      });
      console.log('resourcesToAdd: ', resourcesToAdd);
      await product.removeResources(resourcesToAdd);
      await Journal(ctx, { operatorType: '商品信息 -> 删除资源', code: 200 });
      response = successRes(200);
    } catch (error) {
      console.error(error, '<---- error - 商品信息批量挂载资源');
      await Journal(ctx, { operatorType: '商品信息 -> 删除资源', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // wa
  async wa_s_query (params) {
    let response = null;
    const { ctx } = this;
    try {
      const result = await ctx.model.Product.findAll({
        where: {
          id: params?.id ?? ''
        },
        include: [
          {
            model: ctx.model.ProductClass
          },
          {
            model: ctx.model.Resource,
            through: {
              attributes: {
                exclude: ['id', 'resourceId', 'productId', 'createdAt', 'updatedAt']
              }
            }
          }
        ]
      })
      await Journal(ctx, { operatorType: '商品信息 -> 详情', code: 200 });
      response = successRes(result);
    } catch (error) {
      console.error(error, '<---- error - 商品信息详情');
      await Journal(ctx, { operatorType: '商品信息 -> 详情', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 商品搜索
  async wa_s_search (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const count = await ctx.model.Product.count({
        where: {
          title: {
            [Op.like]: `%${(params?.title ?? '')}%`
          },
        },
      });
      const result = await ctx.model.Product.findAndCountAll({
        where: {
          title: {
            [Op.like]: `%${(params?.title ?? '')}%`
          },
        },
        include: [{
          model: ctx.model.ProductClass
        }, {
          model: ctx.model.Resource,
          through: {
            attributes: {
              exclude: ['id', 'resourceId', 'productId', 'createdAt', 'updatedAt']
            }
          }
        }],
        order: [['id', 'DESC']], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      })
      console.log('result: ', result);
      await Journal(ctx, { operatorType: '商品信息 -> 查询', code: 200 });
      response = successRes({
        records: (result?.rows ?? []),
        total: (count || 0),
        pageSize,
        currentPage
      });
    } catch (error) {
      console.error(error, '<---- error - 商品信息查询');
      await Journal(ctx, { operatorType: '商品信息 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }
}

module.exports = sProduct;
